package cn.kk.communication.controller;
/*
 *@author KK on 2022.11.19 17:18
 */

import cn.kk.communication.entity.Communication;
import cn.kk.communication.service.CommunicationService;
import cn.kk.communication.service.impl.CommunicationServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    CommunicationService communicationService = new CommunicationServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("username");
        try {
            Communication communication = communicationService.getByName(name);
            if (communication != null) {
                request.setAttribute("msg", "该用户已存在");
                request.getRequestDispatcher("register.jsp").forward(request,response);
            } else {
                Communication addCommunication = new Communication(null, name, request.getParameter("pssword"), Long.valueOf(request.getParameter("phone")), request.getParameter("province"));
                int i = communicationService.addUser(addCommunication);
                if (i>0){
                    request.setAttribute("msg", "注册成功");
                    response.setHeader("refresh","3;url=login.jsp");
                }else {
                    request.setAttribute("msg", "注册失败，5秒跳转...");
                    response.setHeader("refresh","5;url=register.jsp");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
